<script setup lang="ts">
import dayjs from 'dayjs'
import { useLoadMore } from 'vue-request'
import { useBeforeOrderStore } from '@/store/beforeOrder'
import { fetchCouponListAPI } from '@/apis/fetchCouponList'
import { useUserInfoStore } from '@/store/userInfo'
import type { Coupon, LoadMoreData } from '@/types/api'

const router = useRouter()
const beforeOrderStore = useBeforeOrderStore()
const userInfoStore = useUserInfoStore()

const navigationDestination = ref<'back' | 'home'>()

onLoad((options) => {
  if (!options?.navigation_destination) {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    return
  }
  navigationDestination.value = options.navigation_destination
})

const selectedTabIndex = ref(0)
const tabConfiguration = ['可使用', '已使用', '已过期']

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Coupon>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Coupon>): Promise<LoadMoreData<Coupon>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchCouponListAPI(
    {
      page: _page.toString(),
      limit: '10',
      type: (selectedTabIndex.value + 1).toString(),
    },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

watch(selectedTabIndex, () => refresh())

function handleViewCouponDetail() {
  router.push({
    name: 'couponDetail',
  })
}

function handleUseCoupon(coupon: Coupon) {
  if (navigationDestination.value === 'back') {
    beforeOrderStore.coupon = coupon
    router.back()
  }
  else {
    router.pushTab('home')
  }
}
</script>

<template>
  <view class="px-32rpx">
    <Tabs
      :selected-index="selectedTabIndex"
      :items="tabConfiguration"
      @change="(i) => selectedTabIndex = i"
    />
  </view>
  <Spacer height="30" />
  <view class="px-24rpx space-y-24rpx">
    <view v-if="dataList.length === 0" class="absolute left-1/2 top-1/2 text-28rpx text-#999999 -translate-1/2">
      暂无数据
    </view>
    <CouponItem
      v-for="item in dataList"
      :key="item.id"
      :type="item.name"
      :price="item.complete_money"
      :minisum="item.money"
      :expire-time="dayjs(item.validate_end_time).format('YYYY.MM.DD')"
      @tap="handleViewCouponDetail"
      @use="handleUseCoupon(item)"
    />
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </view>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'couponList'
style:
  navigationBarTitleText: '优惠券'
</route>
